import { useCallback, useState } from 'react';
import { Tree, useModal, type ColumnProps } from '../../../functionalComponent';
import { cssVar, Layout, iup, useRefCallback, useRefs, useRefState } from '../../../util';
import { ICiteSourceProps } from '../interface';
import { converSourceData, loadSourceConfig } from '../service';
import { findFilterIndexes } from '../utils';
import MasterSlaveTable from './components/MasterSlaveTable';
import ShuttleTable from './components/ShuttleTable';
import ShuttleTableHorizontal from './components/ShuttleTableHorizontal';
import SourceTable from './components/SourceTable';
import SourceTreeTable from './components/SourceTreeTable';
import TreeTable from './components/TreeTable';

/**
 * 来源帮助
 */
export function SourceHelp({
  sourceTree,
  sourceCount,
  busData,
  flowCode,
  defaultSourceCfg,
  detailTables,
  defaultSelectedKeys = []
}: ICiteSourceProps) {
  const [ins] = useModal();
  const [getRef] = useRefs();
  const [popupMode, setPopupMode] = useState(defaultSourceCfg.popupMode);
  const [state, setState] = useRefState<{
    sourceId: string;
    queryItems: any[];
    columns: ColumnProps[];
    masterColumns: ColumnProps[];
    masterQueryItems: any[];
    loading: boolean;
    allowMultiSelect: number | '';
    subTableTitle: string;
    masterFormId?: string;
    treeFieldConfig?: any;
    treeField?: string;
    autoFilterRef: string | number;
    [x: string]: any;
  }>({
    sourceId: defaultSourceCfg.sourceId,
    columns: defaultSourceCfg.columns || [],
    queryItems: defaultSourceCfg.queryItems || [],
    allowMultiSelect: defaultSourceCfg.allowMultiSelect || 0,
    loading: false,
    subTableTitle: defaultSourceCfg.subTableTitle || '',
    masterQueryItems: defaultSourceCfg.masterQueryItems || [],
    masterColumns: defaultSourceCfg.masterColumns || [],
    masterFormId: defaultSourceCfg.masterFormId || '',
    treeFieldConfig: defaultSourceCfg.treeFieldConfig,
    treeField: defaultSourceCfg.masterFormId || '',
    autoFilterRef: defaultSourceCfg.masterFormId || 0
  });

  // 主表选中行
  const [selectedMainRows, setSelectedMainRows] = useState<any[]>([]);
  // 左树右表选中树
  const [orgTreeState, setOrgTreeState] = useState<any>();

  const getSourceId = (sId?) => {
    const sourceId = sId || state.sourceId;
    return sourceId?.indexOf('_') ? iup.split(sourceId, '_')[1] : sourceId;
  };

  // 更新
  const refreshConfig = useCallback(async ({ sourceId: sId }) => {
    const sourceId = getSourceId(sId);
    const {
      columns = [],
      queryItems = [],
      allowMultiSelect,
      popupMode,
      masterQueryItems,
      masterColumns,
      masterFormId,
      treeFieldConfig,
      treeField,
      popupName,
      autoFilterRef
    } = await loadSourceConfig({ sourceId });
    setState({
      loading: false,
      sourceId: sId,
      queryItems,
      columns,
      allowMultiSelect,
      masterQueryItems,
      masterColumns,
      masterFormId,
      treeFieldConfig,
      treeField,
      subTableTitle: popupName,
      autoFilterRef
    });
    setPopupMode(popupMode);
    //  初始化主子表主表、
    setSelectedMainRows([]);
    // 初始化左树右表-左树
    setOrgTreeState('');
  }, []);

  const onSelect = (keys) => {
    refreshConfig({ sourceId: keys[0] });
  };

  ins.setApi({
    async getResult() {
      let ds = getRef('table').current.getApi().getSelectedData() || [];
      let mainRuleHelpInfo;
      // 4-上下穿梭，5-左右穿梭
      if (state.allowMultiSelect === 1 && [4, 5].includes(popupMode)) {
        ds = (getRef('table').current.getApi().getData() || []).filter((row) => row.bizFlowRefed !== 1);
      }
      // 主子表、仅子表多选情况下要传入mainRuleHelpInfo参数
      if (popupMode === 3 && state.allowMultiSelect === 2) {
        mainRuleHelpInfo = {
          sourceDatas: getRef('tableMain').current.getApi().getSelectedData() || [],
          id: state.masterFormId,
          flowCode
        };
      }
      if (ds?.length) {
        const [success, data] = await converSourceData({
          sourceId: getSourceId(),
          flowCode,
          sourceDatas: ds,
          detailTables,
          mainRuleHelpInfo
        });
        if (success) {
          return data || {};
        }
        iup.alert(data);
      } else {
        iup.alert('请先选择数据行！');
      }
      return null;
    }
  });

  const renderTree = () => {
    if (sourceCount < 2) {
      return false;
    }
    return (
      <Layout.Slider size={200} style={{ marginRight: 8 }}>
        <div
          hidden={sourceCount < 2}
          style={{ border: cssVar.border, borderRadius: 4, height: '100%', overflow: 'auto' }}
        >
          <Tree treeData={sourceTree} defaultExpandAll defaultSelectedKeys={[state.sourceId]} onSelect={onSelect} />
        </div>
      </Layout.Slider>
    );
  };

  // 目前只支持单选多选、树，且回填的开关打开
  // 主子表、左树右表、穿梭框等其他需特定联动参数才能展示，暂不支持
  const onDataLoad = useRefCallback((table) => {
    if ((!popupMode || popupMode === 1) && !state.autoFilterRef) {
      const { dataSource = [] } = table.getState() || {};
      const selectIndex = findFilterIndexes(dataSource, (it) => defaultSelectedKeys.includes(it.id));
      table.setSelected(selectIndex);
    }
  });

  // 渲染内容兜底单选list
  // 弹窗样式，0-列表，1-树型，2-左树右表，3-主子表，4-上下穿梭，5-左右穿梭
  const renderTable = () => {
    const globalParams = {
      state,
      popupMode,
      flowCode,
      busData,
      getRef,
      onDataLoad,
      defaultSelectedKeys,
      rowDisable: (row) => row.bizFlowRefed === 1,
      iconVisible: state.autoFilterRef === 1
    };
    // 左右穿梭
    if (popupMode === 5 && state.allowMultiSelect === 1) {
      return <ShuttleTableHorizontal {...globalParams} />;
    }
    // 上下穿梭
    if (popupMode === 4 && state.allowMultiSelect === 1) {
      return <ShuttleTable {...globalParams} />;
    }
    // 主子表
    if (popupMode === 3) {
      return (
        <MasterSlaveTable {...globalParams} dependentState={selectedMainRows} changeDependent={setSelectedMainRows} />
      );
    }
    if (popupMode === 2) {
      return <TreeTable {...globalParams} dependentState={orgTreeState} changeDependent={setOrgTreeState} />;
    }
    if (popupMode == 1) {
      // 树
      return <SourceTreeTable {...globalParams} />;
    }
    // 默认单选、多选
    return <SourceTable {...globalParams} />;
  };

  return (
    <Layout direction="row" autoFit loading={state.loading} style={{ padding: 5 }}>
      {renderTree()}
      <Layout.Flex direction="column">
        <Layout.Flex style={{ border: cssVar.border, borderRadius: 4 }}>{renderTable()}</Layout.Flex>
      </Layout.Flex>
    </Layout>
  );
}
